package com.hp.gxw.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hp.gxw.constant.R;
import com.hp.gxw.entity.*;
import com.hp.gxw.service.*;
import org.apache.catalina.webresources.WarResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@RequestMapping("/api/settlement_deliver_info")
public class SettlementDeliverInfoApi {

    @Autowired
    private ISettlementOrderService orderService;

    @Autowired
    private ISettlementOrderDetailsService detailsService;

    @Autowired
    private ISettlementDeliverInfoService iSettlementDeliverInfoService;

    /**
     * 销售订单数据接收
     * @param map
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public R somain_register(@RequestBody Map<String, Object> map){
        if(map == null){
            return R.error("参数为空");
        }
        SettlementDeliverInfo deliverInfo = new SettlementDeliverInfo();
        if (map.get("orderNo") != null){
            deliverInfo.setOrderNo(map.get("orderNo").toString());
        }else {
            return R.error("内部订单号必填！");
        }
        if (map.get("customerOrder") != null){
            deliverInfo.setCustomerOrder(map.get("customerOrder").toString());
        }
        if (map.get("customerCode") != null){
            deliverInfo.setCustomerCode(map.get("customerCode").toString());
        }else {
            return R.error("客户编码必填！");
        }
        if (map.get("customerName") != null){
            deliverInfo.setCustomerName(map.get("customerName").toString());
        }else {
            return R.error("客户名称必填！");
        }
        if (map.get("cinvcode") != null){
            deliverInfo.setCinvcode(map.get("cinvcode").toString());
        }else {
            return R.error("存货编码必填！");
        }
        if (map.get("cinvname") != null){
            deliverInfo.setCinvname(map.get("cinvname").toString());
        }else {
            return R.error("存货名称必填！");
        }
        if (map.get("cbatch") != null){
            deliverInfo.setCbatch(map.get("cbatch").toString());
        }
        if (map.get("qty") != null){
            String qty = map.get("qty").toString();
            deliverInfo.setQty(BigDecimal.valueOf(Double.parseDouble(qty)));
        }else {
            return R.error("发货数量必填！");
        }
        if (map.get("deliverDate") != null){
            String deliverDate = map.get("deliverDate").toString();
            //验证日期格式
            if (isValidDateFormat(deliverDate,"yyyy-MM-dd")) {
                deliverInfo.setDeliverDate(DateUtil.parse(deliverDate,"yyyy-MM-dd"));
            }else {
                return R.error("发货日期日期格式不正确(yyyy-MM-dd)！");
            }
        }else {
            return R.error("发货日期必填！");
        }
        if (map.get("inOutType") != null){
            deliverInfo.setInOutType(map.get("inOutType").toString());
        }else {
            return R.error("出入库类型必填！");
        }

        //校验内部订单号是否存在
        SettlementOrder one = orderService.getOne(Wrappers.lambdaQuery(SettlementOrder.class).eq(SettlementOrder::getOrderNo, deliverInfo.getOrderNo()));
        if (null == one){
            return R.error("未找到结算单！");
        }
        if (!one.getCustomerCode().equals(deliverInfo.getCustomerCode())){
            return R.error("客户编码与结算单客户编码不一致！");
        }
        //校验存货编码是否存在detail中
        long count = detailsService.count(Wrappers.lambdaQuery(SettlementOrderDetails.class)
                        .eq(SettlementOrderDetails::getMasterId,one.getId())
                        .eq(SettlementOrderDetails::getCinvcode, deliverInfo.getCinvcode())
        );
        if (count <= 0){
            return R.error("结算单明细行中不存在当前存货编码！");
        }
            // 查找添加的表中有没有相同的数据
        LambdaQueryWrapper<SettlementDeliverInfo> settlementDeliverInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        settlementDeliverInfoLambdaQueryWrapper
                .eq(SettlementDeliverInfo::getOrderNo,deliverInfo.getOrderNo())
                .eq(SettlementDeliverInfo::getCinvcode,deliverInfo.getCinvcode())
                .eq(SettlementDeliverInfo::getCbatch,deliverInfo.getCbatch())
                .eq(SettlementDeliverInfo::getQty,deliverInfo.getQty());
        List<SettlementDeliverInfo> list = iSettlementDeliverInfoService.list(settlementDeliverInfoLambdaQueryWrapper);
        if (list.isEmpty()){
            return R.error("已存在相同数据");
        }
        try {
            iSettlementDeliverInfoService.saveInfo(deliverInfo);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("接口异常");
        }
        return R.ok("写入成功");
    }

    /**
     * 判断字符串是否为指定格式的日期时间
     *
     * @param dateStr    需要检查的日期字符串
     * @param dateFormat 指定的日期格式，例如："yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd" 等
     * @return 如果字符串是指定格式的日期时间，返回 true;否则返回 false。
     */

    public boolean isValidDateFormat(String dateStr, String dateFormat) {
        if (ObjectUtil.isEmpty(dateStr)) {
            return false;
        }
        try {
            DateUtil.parse(dateStr, dateFormat); // 将字符串解析为日期对象，如果解析成功，则说明字符串是有效的日期格式；否则说明字符串不是有效的日期格式。
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
